#!/bin/bash
########################################################################
# (C) Copyright 2008 Muhammed Uluyol
########################################################################
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
########################################################################
#
# This script adds entries to the database

[ -f lib_helper.cfg ] || echo "CANT FIND CONFIG"
source lib_helper.cfg

if [ -z "$1" ]; then
	echo "No argument specified, type $0 --help for more options"
	exit 77
fi

case $1 in
	--title|-t)
		export SEARCH_OPTION="TITLE"
		;;
	--author|-a)
		export SEARCH_OPTION="AUTHOR"
		;;
	--summary|-s)
		export SEARCH_OPTION="SUMMARY"
		;;
	--tags|-g)
		export SEARCH_OPTION="TAGS"
		;;
	*)
		echo -e "Usage: $0 [OPTION]"
		echo -e "  --title/-t\t\t\t\t Search based on the title"
		echo -e "  --author/-a\t\t\t\t Search based on the author"
		echo -e "  --summary/-s\t\t\t\t Search based on the summary"
		echo -e "  --tags/-g\t\t\t\t Search based on the tags"
		echo -e "  --help/-h\t\t\t\t Display this help message"
		exit 66
		;;
esac

clear
echo -e "\033[1mEnter the book `echo $SEARCH_OPTION | tr [:upper:] [:lower:]`, DO NOT PRESS ENTER UNTIL DONE TYPING\033[0m"
read -p "$SEARCH_OPTION: " title
echo "Searching..."
for book in `ls -1 $DB_DIR | grep \.bk`; do
	book=$DB_DIR/$book
	if (grep $SEARCH_OPTION $book | grep -i $title) &>/dev/null; then
		clear
		echo "Is this it?"
		cat $book
		read -p "[Y/n]" yesno
		yesno=$(echo $yesno | tr [:upper:] [:lower:])
		if [ x$yesno != x"no" -a x$yesno != x"n" ]; then
			read -p "Enter book code: " code
			echo "Adding `basename $book` to DB"
			echo "`basename $book` $code" >>$DB_NAME.bkdb
			break
		fi
	fi
done
